package com.kh.pajx.sop.service.order.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kh.pajx.sop.base.BaseServiceImpl;
import com.kh.pajx.sop.dao.order.IReplaceCardOrderDetailDao;
import com.kh.pajx.sop.dao.student.IStudentInfoDao;
import com.kh.pajx.sop.domain.TempExportExcel;
import com.kh.pajx.sop.domain.order.ReplaceCardOrderDetail;
import com.kh.pajx.sop.domain.student.StudentInfo;
import com.kh.pajx.sop.service.order.IReplaceCardOrderDetailService;
import com.kh.pajx.sop.util.excel.ExportExcel;
import com.kh.pajx.sop.util.page.QueryHelper;

/**
 * 补卡单据明细业务逻辑实现类
 * 
 * @author: azzcsimp
 * @Createdate: 2014年11月11日 上午10:26:50
 */
@Service
@Transactional
public class ReplaceCardOrderDetailServiceImpl extends BaseServiceImpl<ReplaceCardOrderDetail> implements IReplaceCardOrderDetailService {

    @Resource
    private IReplaceCardOrderDetailDao replaceCardOrderDetailDao;
    
    @Resource
    private IStudentInfoDao studentInfoDao;

    @Override
    public void list(ReplaceCardOrderDetail model, int pageNum, int numPerPage) throws Exception {
	QueryHelper queryHelper = new QueryHelper(ReplaceCardOrderDetail.class, "o");
	if (StringUtils.isNotEmpty(model.getStuName())) {
	    queryHelper.addCondition("(o.stuName like ? or o.stuNo = ?)", "%" + model.getStuName() + "%", model.getStuName());
	}
	if (model.getRcodType() != null) {
	    if (model.getRcodType() > 0) {
		queryHelper.addCondition("o.rcodType=?", model.getRcodType());
	    }
	}
	queryHelper.addCondition("o.rcoId=?", model.getRcoId());
	queryHelper.addOrderProperty("o.stuNo", true);
	System.out.println(queryHelper.getListQueryHql());
	queryHelper.preparePageBean(replaceCardOrderDetailDao, pageNum, numPerPage);
    }

    @Override
    public List<ReplaceCardOrderDetail> getByRcoId(String rcoId) throws Exception {
	return replaceCardOrderDetailDao.getDetailByRcoId(rcoId);
    }

    @Override
    public String exportExcelOrderDetail(String rcoId, String sclNo, String path, String fileName) throws Exception {
	// 判断是否有临时文件夹，没有则创建
	this.createDir(path);
	// 生成压缩包
	byte[] buffer = new byte[1024];
	String strZipName = path + "/" + System.currentTimeMillis() + fileName.replaceAll("[.]", "") + ".zip";
	ZipOutputStream zipOps = new ZipOutputStream(new FileOutputStream(strZipName));
	// FileInputStream fis = null;
	InputStream fis = null;
	List<ReplaceCardOrderDetail> recods = replaceCardOrderDetailDao.getDetailByRcoId(rcoId);
	List<TempExportExcel> list = new ArrayList<TempExportExcel>();
	Map<String, String> stuPhoto = null;
	String stuIds = "(";
	int i = 1;
	for (ReplaceCardOrderDetail rcod : recods) {
	    if (i < recods.size()) {
		stuIds += "'" + rcod.getStuId() + "',";
	    } else {
		stuIds += "'" + rcod.getStuId() + "')";
	    }
	    i++;

	}
	stuPhoto = replaceCardOrderDetailDao.getStuPhoto(stuIds);
	try {
	    for (ReplaceCardOrderDetail rcod : recods) {
			TempExportExcel t = new TempExportExcel();
			StudentInfo student = studentInfoDao.getById(rcod.getStuId());
			t.setStuName(rcod.getStuName());
			String sex = "未知";
			if(student.getStuSex()!=null){
				if(student.getStuSex()==1){
					sex = "男";
				}else if(student.getStuSex()==2){
					sex = "女";
				}
			}
			t.setSex(sex);
			t.setStuNo(rcod.getStuNo());
			t.setGraName(rcod.getGraName());
			t.setClsName(rcod.getClsName());
			t.setInsclDate(student.getInSclDate());
			t.setSclNo(student.getStuSclNo());
			String stayFlag = "未知";
			if(student.getStayFlag()!=null){
				if(student.getStayFlag()==1){
					stayFlag = "住校";
				}else if(student.getStayFlag()==2){
					stayFlag = "走读";
				}
			}
			t.setStayType(stayFlag);
			if (rcod.getRcodType() == 1) {
			    t.setOrderType("印刷错误");
			} else if (rcod.getRcodType() == 2) {
			    t.setOrderType("卡片损坏");
			} else if (rcod.getRcodType() == 3) {
			    t.setOrderType("卡片丢失");
			}
	
			t.setPrice(rcod.getRcodPrice() + "");
			list.add(t);
	
			// 处理图片到zip压缩包里面
			if (stuPhoto.get(rcod.getStuId()) != null) {
			    // fis = new
			    // FileInputStream("E://static//PhotoData//student//"+sclNo+"//"+stuPhoto.get(rcod.getStuId()));
			    // fis = new
			    // FileInputStream("http://img.tuanhuopu.com/75/37/753759a74568f3317036d2adf7347fc5.png");
			    // URL url = new
			    // URL("http://img.tuanhuopu.com/75/37/753759a74568f3317036d2adf7347fc5.png");
			    try {
				URL url = new URL("http://static.pajx.com.cn/PhotoData/Student/" + sclNo + "/" + stuPhoto.get(rcod.getStuId()) + ".jpg");
				HttpURLConnection httpUrlCon = (HttpURLConnection) url.openConnection();
				httpUrlCon.setDoInput(true);
				httpUrlCon.connect();
				fis = httpUrlCon.getInputStream();
				if (fis != null) {
				    // System.out.println("file size is:"+httpUrlCon.getContentLength());
				    zipOps.putNextEntry(new ZipEntry(stuPhoto.get(rcod.getStuId()) + ".jpg"));
				    int len;
				    while ((len = fis.read(buffer)) > 0) {
					zipOps.write(buffer, 0, len);
				    }
				    zipOps.closeEntry();
				    fis.close();
				}
			    } catch (Exception e) {
				System.out.println("卡号为：" + rcod.getStuNo() + "的学生" + rcod.getStuName() + "照片生成图片失败！================>可能" + e.getMessage() + "不存在");
			    }
			}

	    }

	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    // 生成excel临时文件
	    String[] heards = { "姓名","性别", "卡号", "年级", "班级","学籍号","入学年份", "住校标识","补卡类型", "价格" };
	    ExportExcel<TempExportExcel> ex = new ExportExcel<TempExportExcel>();
	    String excelPath = strZipName.split("[.]")[0] + ".xls";
	    OutputStream out = new FileOutputStream(excelPath);
	    HSSFWorkbook wb = ex.exportExcel(heards, list);
	    wb.write(out);
	    out.close();
	    // 压缩excel
	    fis = new FileInputStream(excelPath);
	    zipOps.putNextEntry(new ZipEntry("订单详情列表.xls"));
	    int len;
	    while ((len = fis.read(buffer)) > 0) {
		zipOps.write(buffer, 0, len);
	    }
	    zipOps.closeEntry();
	    fis.close();
	    zipOps.close();
	    File fexcel = new File(excelPath);
	    if (fexcel.exists()) {
		fexcel.delete();
	    }
	}
	return strZipName;
    }

    /**
     * 判断是否存在一个文件夹， 若不存在则创建一个文件夹， 本类中使用
     */
    private void createDir(String path) {
	File dir = new File(path);
	if (!dir.exists()) {
	    dir.mkdirs();
	}
    }

}
